package com.cimr.comm.controller.manager;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.cimr.comm.bo.MenuBo;
import com.cimr.comm.dto.HttpResult;
import com.cimr.comm.dto.LayuiTableData;
import com.cimr.comm.enums.MenuTargetEnum;
import com.cimr.comm.service.MenuService;
import com.cimr.comm.service.PermissionService;
import com.cimr.comm.token.TokenUtil;
import com.cimr.comm.util.IdUtil;
import com.cimr.dto.MenuTargetDto;
import com.cimr.dto.MenuTree;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * Created by liqi on 2017/12/27.
 * liqiwork@qq.com
 */
@Controller
@RequestMapping("/menuManager/ajax")
public class MenuManagerAjaxController {

    @RequestMapping({"/getMenuTreeByCurrentUser"})
    @ResponseBody
    public HttpResult getMenuTreeByCurrentUser() {
        String userId = TokenUtil.getUserId();
        Set permissionSet = permissionService.findPermissionByUserId(userId);

        List<MenuBo> menuList = menuService.getMenuList();
        Map menusMap = new HashMap();
        List<MenuBo> menuListByUser = new ArrayList<>();
        for (int i = 0; i < menuList.size(); i++) {
            if (permissionSet.contains(menuList.get(i).getMenuKey())) {
                menuListByUser.add(menuList.get(i));
                menusMap.put(menuList.get(i).getId(), menuList.get(i));
            }
        }

        for (int j = 0; j < menuListByUser.size(); j++) {
            if (!"0".equals(menuListByUser.get(j).getParentId())) {
                // 非一级菜单
                MenuBo menu = (MenuBo) menusMap.get(menuListByUser.get(j).getParentId());
                if (menu!=null) {
                    List<MenuBo> menuChildren = menu.getChildren();
                    if (menuChildren==null) {
                        menuChildren = new ArrayList<>();
                    }
                    menuChildren.add(menuListByUser.get(j));
                    menu.setChildren(menuChildren);
                }
            }
        }

        List<MenuBo> resultMenuList = new ArrayList<>();
        for (int k = 0; k <menuListByUser.size(); k++) {
            if (menuListByUser.get(k).getLevel()==1) {
                resultMenuList.add(menuListByUser.get(k));
            }
        }

        HttpResult result = new HttpResult(true, "成功");
        result.setData(resultMenuList);
        return result;
    }

    @RequiresPermissions(value = {"menuManager:getMenuList", "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"getMenuList"})
    @ResponseBody
    public LayuiTableData getMenuList(@RequestParam(required = true,defaultValue = "1") Integer page,
                                      @RequestParam(required = false,defaultValue = "10") Integer limit,
                                      @RequestParam(required = false) String  menuName) {
        PageHelper.startPage(page, limit);
        List<MenuBo> list = menuService.getMenuListWithName(menuName);
        PageInfo<MenuBo> pageInfo = new PageInfo(list);
        List<MenuBo> list1 = menuService.getMenuListWithName(menuName);
        LayuiTableData result = new LayuiTableData();
        result.setCode(0);
        result.setMsg("");
        result.setCount(list1.size());
        result.setData(pageInfo.getList());
        return result;
    }

    /**
     *@auther zengfan
     *@date 2018/1/12 10:48
     *@params  * @param
     *将菜单数据组装为树形结构
     **/
//    @RequiresPermissions(value = {"menuManager:getMenuTableTree", "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"getMenuTableTree"})
    @ResponseBody
    public HttpResult getMenuTableTree(@RequestParam(required = false) String  menuName) {
        HttpResult result = new HttpResult(true, "");
        List<MenuBo> list = menuService.getMenuListWithName(menuName);
        List<MenuTree> levl1List = new ArrayList<>();
        List<MenuTree> levl2List = new ArrayList<>();
        for (MenuBo mb:list){
            if (mb.getLevel()==1){
                MenuTree mt = new MenuTree();
                mt.setId(mb.getId());
                mt.setName(mb.getMenuName());
                mt.setMenuKey(mb.getMenuKey());
                mt.setParentId(mb.getParentId());
                mt.setOrderId(mb.getOrderId());
                mt.setLevel(mb.getLevel());
                mt.setUrl(mb.getHref());
                if(mb.getTarget().equals("_self")){
                    mt.setTarget("本页面");
                }
                if(mb.getTarget().equals("_blank")){
                    mt.setTarget("新页面");
                }
                if(mb.getComment()==null){
                    mt.setComment("");
                }else{
                    mt.setComment(mb.getComment());
                }
                levl1List.add(mt);
            }
            if (mb.getLevel()==2){
                MenuTree mt = new MenuTree();
                mt.setId(mb.getId());
                mt.setName(mb.getMenuName());
                mt.setMenuKey(mb.getMenuKey());
                mt.setParentId(mb.getParentId());
                mt.setOrderId(mb.getOrderId());
                mt.setLevel(mb.getLevel());
                mt.setUrl(mb.getHref());
                if(mb.getTarget().equals("_self")){
                    mt.setTarget("本页面");
                }
                if(mb.getTarget().equals("_blank")){
                    mt.setTarget("新页面");
                }
                if(mb.getComment()==null){
                    mt.setComment("");
                }else{
                    mt.setComment(mb.getComment());
                }
                levl2List.add(mt);
            }
        }
        for (MenuTree mb1:levl1List){
            List<MenuTree> mb2List = new ArrayList<MenuTree>();
            for (MenuTree mb2:levl2List){
                if (mb1.getId().equals(mb2.getParentId())){
                    mb2List.add(mb2);
                }
            }
            mb1.setChildren(mb2List);
        }
        result.setData(levl1List);
        return result;
    }

    /**
     * 将菜单数据组装为树形结构
     * @param menuName
     * @return
     */
    @RequestMapping({"getMenuTreeTable"})
    @ResponseBody
    public HttpResult getMenuTreeTable(@RequestParam(required = false) String  menuName) {
        HttpResult result = new HttpResult(true, "");
        List<MenuBo> list = menuService.getMenuListWithName(menuName);
        JSONArray jsonArray = new JSONArray(list);
        result.setData(jsonArray);
        return result;
    }

    /**
     *@auther zengfan
     *@date 2018/1/3 15:31
     *@params  * @param null
     *用户编辑菜单（根据ID查询菜单数据，同时查询一级菜单，菜单打开类型的枚举）
     **/
//    @RequiresPermissions(value = {"menuManager:getMenuInfoById", "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"getMenuInfoById"})
    @ResponseBody
    public HttpResult getMenuInfoById(String id) {
        HttpResult result = new HttpResult(true, "");
        MenuBo menuBo = menuService.getMenuById(id);
        List<MenuBo> parentList = menuService.getMenuList();
        for (int i = parentList.size()-1;i>= 0;i--){
            if (parentList.get(i).getLevel()!=1){
                parentList.remove(i);
            }
        }
        List<MenuTargetDto> MenuTagerList = new ArrayList<>();
        for (MenuTargetEnum menu:MenuTargetEnum.values()){
            MenuTargetDto mtd = new MenuTargetDto();
            mtd.setKey(menu.getKey());
            mtd.setName(menu.getName());
            MenuTagerList.add(mtd);
        }
        Map map = new HashMap();
        map.put("menuBo",menuBo);
        map.put("menuTarget", MenuTagerList);
        map.put("parentList", parentList);
        result.setData(map);
        return result;
    }

    /**
     *@auther zengfan
     *@date 2018/1/3 16:26
     *@params  * @param null
     *用户新增菜单（查询一级菜单，菜单打开类型的枚举）
     **/
    @RequestMapping({"addMenuInfoById"})
    @ResponseBody
    public HttpResult addMenuInfoById() {
        HttpResult result = new HttpResult(true, "");
        List<MenuBo> parentList = menuService.getMenuList();
        for (int i = parentList.size()-1;i>= 0;i--){
            if (parentList.get(i).getLevel()!=1){
                parentList.remove(i);
            }
        }
        List<MenuTargetDto> MenuTagerList = new ArrayList<>();
        for (MenuTargetEnum menu:MenuTargetEnum.values()){
            MenuTargetDto mtd = new MenuTargetDto();
            mtd.setKey(menu.getKey());
            mtd.setName(menu.getName());
            MenuTagerList.add(mtd);
        }
        Map map = new HashMap();
        map.put("menuTarget", MenuTagerList);
        map.put("parentList", parentList);
        result.setData(map);
        return result;
    }

    //菜单保存
    @RequiresPermissions(value = {"menuManager:save",
                                  "menuManager:saveMenu",
                                  "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"saveMenu"})
    @ResponseBody
    public HttpResult saveMenu(String id,String menuKey, String menuName, String parentId, Integer level, String comment, Float orderId, String target, String href) {
        int resultStatus1;
        if(id != null && !"".equals(id)) {
            resultStatus1 =  this.menuService.updateMenu(id, menuKey, menuName, parentId, level, comment, orderId, target, href);
        } else {
            resultStatus1 = this.menuService.insertMenu(IdUtil.getId().toString(), menuKey, menuName, parentId, level, comment, orderId, target, href);
        }

        HttpResult result = new HttpResult(true, "");
        if(resultStatus1 == 0) {
            result.setSuccess(false);
        }

        return result;
    }

    //菜单删除
    @RequiresPermissions(value = {"menuManager:delete",
                                  "menuManager:deleteMenu",
                                  "cimrFrame:operation:passkey"}, logical = Logical.OR)
    @RequestMapping({"deleteMenu"})
    @ResponseBody
    public HttpResult deleteMenu(String id,Integer level) {
        HttpResult result = new HttpResult(true, "");
        int resultStatus = 0;
        if(level == 1){
            int resultStatusId = this.menuService.deleteMenuById(id);
            int resultStatusParentId = this.menuService.deleteMenuListByParentId(id);
            resultStatus = resultStatusId+resultStatusParentId;
        }
        if(level==2){
            resultStatus = this.menuService.deleteMenuById(id);
            if(resultStatus == 0) {
                result.setSuccess(false);
            }
        }
        return result;
    }

    @RequestMapping({"getMenuListByMenuKey"})
    @ResponseBody
    public HttpResult getMenuListByKey(String  menuKey) {
        List<MenuBo> list = menuService.getMenuListByKey(menuKey);
        HttpResult result = new HttpResult(true, "");
        if(list!=null) {
            if(list.size()==0){
                result.setData(null);
            }else{
                result.setData(list);
            }
        }
        return result;
    }

    /**
     *@auther zengfan
     *@date 2018/1/17 10:28
     *@params  * @param null
     *在编辑时通过menuKey查询菜单，并排除出当前的menuKey的菜单
     **/
    @RequestMapping({"getMenuListByMenuKeyOutCurrent"})
    @ResponseBody
    public HttpResult getMenuListByMenuKeyOutCurrent(String id,String  menuKey) {
        List<MenuBo> list = menuService.getMenuListByKey(menuKey);
        HttpResult result = new HttpResult(true, "");
        if(list!=null && list.size()!=0){
            if (list.get(0).getId().equals(id)){
                result.setData(null);
            }else {
                result.setData(list);
            }
        }else{
            result.setData(null);
        }
        return result;
    }

    @Autowired
    private MenuService menuService;
    @Autowired
    private PermissionService permissionService;
}
